#include "ComponentBehaviorSelector.h"
#include "Components/ComponentCreature.h"
#include "Components/ComponentHealth.h"

#include "GameSingleton.h"
#include "GameRegistry.hpp"
#include "GameThreadPool.hpp"
#include "Game/TableComponent.hpp"

/**
 *
 * 这个已经跟原版一致了，不需要改动什么
 *
 */

using namespace PocketSurvival::Engine;

namespace PocketSurvival
{

    void ComponentBehaviorSelector::setIsDisableBehavior(bool value)
    {
        m_isDisableBehavior = value;
        if (value == false)
        {
            for (ComponentBehavior *behavior : m_behaviorVec)
            {
                behavior->setActive(false);
            }
        }
    }

    void ComponentBehaviorSelector::update(float dt)
    {
        if (m_isDisableBehavior == true)
        {
            return;
        }
        ComponentBehavior *componentBehavior = nullptr;
        if (componentCreature->componentHealth->health > 0.0f)
        {
            float num = 0.0f;
            for (ComponentBehavior *behavior : m_behaviorVec)
            {
                float importanceLevel = behavior->getImportanceLevel();
                if (importanceLevel > num)
                {
                    num = importanceLevel;
                    componentBehavior = behavior;
                }
            }
        }
        for (ComponentBehavior *behavior2 : m_behaviorVec)
        {
            if (behavior2 == componentBehavior)
            {
                if (behavior2->isActive() == false)
                {
                    behavior2->setActive(true);
                }
            }
            else if (behavior2->isActive())
            {
                behavior2->setActive(false);
            }
        }
    }


    static const std::string componentName = "BehaviorSelector";
    const std::string &ComponentBehaviorSelector::getName() const
    {
        return componentName;
    }
    const std::string &ComponentBehaviorSelector::GetName()
    {
        return componentName;
    }
    void ComponentBehaviorSelector::load(const nlohmann::json &jsonData)
    {
        TableComponent *tableCom = GameSingleton::gameRegistry->get<TableComponent *>(entity);
        componentCreature = tableCom->findComponent<ComponentCreature>();

        tableCom->dynamicFindComponent<ComponentBehavior>(m_behaviorVec);
    }

} // namespace PocketSurvival
